package example.controller;

import example.config.MyWebAppConfigurer;
import example.dao.DataTableDto;
import example.dao.Result;
import example.pojo.User;
import example.service.FileService;
import example.service.UserService;
import example.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

//import example.service.AnswerService;
//import example.service.PaperService;
//import example.service.QuestionService;

@Controller
@RequestMapping({"/uservue"})
public class UserVueController {
//    @Autowired  可以改成 @Resource
    @Autowired
    TokenUtil tokenUtil;
    private Map<String, Object> map;
    @Autowired
    private FileService fileService;

    @Autowired
    private UserService userService;

    @Autowired()
    private MyWebAppConfigurer config;


    @RequestMapping({"/user_list"})
    public String user_list(HttpServletRequest req) throws Exception {
        List<User> users = new ArrayList<User>();
        users = userService.getUserlistAll();

//        for(User tuser : users) {
//            if (tuser.getUserimg()==null || tuser.getUserimg()==""){
//                tuser.setUserimg("/upload/user.png");
//            }
//        }
        //users.add(user);
        req.setAttribute("users", users);
        return "system/user/user_list";
    }

    @RequestMapping({"/getAllUserList"})
    @ResponseBody
    public List<User> getAllUserList(HttpServletRequest req) throws Exception {
        List<User> users = new ArrayList<User>();
        users = userService.getUserlistAll();
        return users;
    }

    // 用户退出user
    @RequestMapping({"/exit"})
    public String exit(User user, HttpServletRequest req, HttpSession session) throws Exception {
        session.removeAttribute("user");
        session.removeAttribute("id");

        return "redirect:../";
    }

    // 取得当前用户ID
    @RequestMapping({"/getuseridnow"})
    @ResponseBody
    public String getUserIdNow(HttpServletRequest req, HttpSession session) throws Exception {
        return String.valueOf(session.getAttribute("id"));
    }

//    @RequestMapping({"/insert0"})
//    public String insert0(HttpSession session, HttpServletRequest req) throws Exception {
//        return "system/user/user_add";
//    }


    @RequestMapping({"/getUsersTotal"})
    @ResponseBody
    public Integer getUsersTotal(User user, HttpSession session, HttpServletRequest req) throws Exception {
        Result result = new Result();
        List<User> users = userService.getUserlistByName(user);
        if (users != null && users.size() >= 0) {
            return users.size();
        } else {
            return 0;
        }

    }


    @RequestMapping({"/getUsers"})
    @ResponseBody
    public List<User> getUsers(String name, Integer start,
                               Integer pageSize) throws Exception {
        User user = new User();
        user.setName(name);
        List<User> list;
        if (user != null && user.getName() != null && user.getName() != "") {
            list = userService.getUserlistByName(user);
        } else {
            list = userService.getUserlistAll();
        }

        int endIndex = start + pageSize;

        if (list == null) {
            list = new ArrayList<User>();
        }
        if (list.size() < endIndex) {
            endIndex = list.size();
        }
        List<User> listObject = new ArrayList<User>();
        for (int i = start; i < endIndex; i++) {
//              <th>照片</th>
//                <th>ID</th>
//                <th>姓名</th>
//                <th>邮箱</th>
//                <th>电话</th>
//                <th>操作</th>
            user = new User();
            ;
            user.setUserimg(list.get(i).getUserimg());
            user.setId(list.get(i).getId());
            user.setName(list.get(i).getName());
            user.setEmail(list.get(i).getEmail());
            user.setPassword(list.get(i).getPassword());
            user.setPhonenumber(list.get(i).getPhonenumber());
            listObject.add(user);
        }
        return listObject;

    }

    @RequestMapping({"/getUsersByName"})
    @ResponseBody
    public List<User> getUsersByName(String name) throws Exception {
        User user = new User();
        user.setName(name);
        List<User> list;
        if (user != null && user.getName() != null && user.getName() != "") {
            list = userService.getUserlistByName(user);
        } else {
            list = userService.getUserlistAll();
        }

        if (list == null) {
            list = new ArrayList<User>();
        }

        List<User> listObject = new ArrayList<User>();
        for (int i = 0; i < list.size(); i++) {
//              <th>照片</th>
//                <th>ID</th>
//                <th>姓名</th>
//                <th>邮箱</th>
//                <th>电话</th>
//                <th>操作</th>
            user = new User();
            ;
            user.setUserimg(list.get(i).getUserimg());
            user.setId(list.get(i).getId());
            user.setName(list.get(i).getName());
            user.setPassword(list.get(i).getPassword());
            user.setEmail(list.get(i).getEmail());
            user.setPhonenumber(list.get(i).getPhonenumber());
            listObject.add(user);
        }
        return listObject;

    }

    @RequestMapping({"/addSaveUserData"})
    @ResponseBody
    public Result addSaveUserData(User user, HttpSession session, HttpServletRequest req) throws Exception {

        Result result = new Result();

        if (userService.selectByName(user)) {
            user = userService.insert(user);
            if (user != null) {
                result.setResult("success");
                result.setMessage("操作完成");
                result.setImgUrl(user.getUserimg());
            } else {
                result.setResult("error");
                result.setMessage("操作失败");
                result.setImgUrl("");
            }
        } else {
            result.setResult("error");
            result.setMessage("操作失败");
            result.setImgUrl("");
        }
        return result;
    }

    // 用户信息修改完成
    @RequestMapping({"/updateSaveUserData"})
    @ResponseBody
    public Result updateSaveUserData(User newuser, HttpServletRequest req, HttpSession session) throws Exception {
        User user = userService.getUserById(newuser.getId());
        // 删除原来的图片
        if (user.getUserimg() != null
                && !(user.getUserimg().equals(""))
                && !(newuser.getUserimg().equals(user.getUserimg()))) {
            String filePath = config.ROOT_PATH + user.getUserimg();
            fileService.deleteFile(filePath);
        }
        //修改信息
        user.setUserimg(newuser.getUserimg());
        user.setName(newuser.getName());
        user.setPassword(newuser.getPassword());
        user.setEmail(newuser.getEmail());
        user.setPhonenumber(newuser.getPhonenumber());
        Result result = new Result();
        user = userService.update(user);
        if (user != null) {
            result.setResult("success");
            result.setMessage("操作完成");
            result.setImgUrl(user.getUserimg());
        } else {
            result.setResult("error");
            result.setMessage("操作失败");
            result.setImgUrl("");
        }
        return result;
    }


    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(User user, HttpServletRequest req, HttpSession session) throws Exception {
        // 当前用户
        //User user= (User) session.getAttribute("user");
        user = userService.getUserById(user.getId());
        String imgName = "";
        if (user.getUserimg() != null && !(user.getUserimg().equals(""))) {
            imgName = user.getUserimg().replaceFirst(config.uploadPath, "");
            String filePath = config.ROOT_PATH + imgName;
            fileService.deleteFile(filePath);
        }
        Result result = new Result();
        userService.deleteUserById(user);
        result.setResult("success");
        result.setMessage("操作完成");
        result.setImgUrl(user.getUserimg());
        return result;

    }


    @RequestMapping({"/forgetPwd"})
    public String forgetPwd() {
        return "forgetPwd";
    }

    @RequestMapping({"/reSetPwd"})
    public String reSetPwd() {
        return "reSetPwd";
    }


    @RequestMapping({"/getPwd"})
    public String getPwd(User user, HttpServletRequest req, HttpSession session) throws Exception {
        User tuser = userService.getPwdByPhoneOrMail(user);

        if (tuser == null) {
            req.setAttribute("mes", "邮箱有误!");

        } else {
            req.setAttribute("mes", "你的密码是：" + tuser.getPassword());

        }
        return "forgetPwd";
    }


// 用户查询

    @RequestMapping({"/getUserlistByName"})
    @ResponseBody
    public List<User> getUserlistByName(User user, HttpServletRequest req, HttpSession session) throws Exception {
        List<User> userlist = userService.getUserlistByName(user);
        return userlist;
    }

    @RequestMapping({"/getUserById"})
    @ResponseBody
    public User getUserById(User user, HttpServletRequest req, HttpSession session) throws Exception {
        user = userService.getUserById(user.getId());
        return user;
    }

    /*
         读取表单数据，分页
         *
         */
    @RequestMapping({"/part"})
    @ResponseBody
    public DataTableDto part(DataTableDto dataTableDto,
                             User user, int start,
                             int length, String draw) throws Exception {


        List<User> list;
        if (user != null && user.getName() != null && user.getName() != "") {
            String name = user.getName();
            list = userService.getUserlistByName(user);
        } else {
            list = userService.getUserlistAll();
        }


        int endIndex = dataTableDto.start + dataTableDto.length;
        if (list == null) {
            list = new ArrayList<User>();
        }
        if (list.size() < endIndex) {
            endIndex = list.size();
        }
        List<Object> listObject = new ArrayList<Object>();
        for (int i = dataTableDto.start; i < endIndex; i++) {
//              <th>照片</th>
//                <th>ID</th>
//                <th>姓名</th>
//                <th>邮箱</th>
//                <th>电话</th>
//                <th>操作</th>
            Object[] objects = new Object[6];
            objects[0] = list.get(i).getUserimg();
            objects[1] = list.get(i).getId();
            objects[2] = list.get(i).getName();
            objects[3] = list.get(i).getEmail();
            objects[4] = list.get(i).getPhonenumber();
            objects[5] = list.get(i).getId();
            listObject.add(objects);
        }
        dataTableDto.recordsTotal = list.size();
        dataTableDto.recordsFiltered = list.size();
        dataTableDto.data = listObject;

        return dataTableDto;

    }

    // 用户登录后自动跳转到用户模块
    @RequestMapping({"/login"})
    @ResponseBody
    public Result login(User user, HttpServletRequest req, HttpServletResponse res, HttpSession session) throws Exception {
        map = userService.login(user);
        Result result = new Result();

//        服务器跳转和客户端跳转的区别：
//        1.服务器跳转时，地址栏的地址不改变；而客户端跳转的时候，地址栏的地址是会变化的;
//        2.服务器跳转的时候，能够通过request（或者是 model）来传递数据;而客户端跳转的时候是不能传递数据的

        if (map.size() == 0) {
            result.setResult("error");
            result.setMessage("账号密码有误");
            result.setImgUrl("");
            return result;
        }
        for (Entry<String, Object> one : map.entrySet()) {
            if (one.getKey().equals("user")) {
                User reuser = (User) one.getValue();
                session.setAttribute("user", reuser);
                session.setAttribute("id", reuser.getId());
            }
        }
        result.setResult("success");
        result.setMessage("登录成功");
        result.setImgUrl(user.getUserimg());

        List<User> users = new ArrayList<User>();
        users = userService.getUserlistAll();
        req.setAttribute("users", users);
        /**
         * 使用 /login 请求获得 token, /login 不经过拦截器
         */
        //解决办法就是加上这一行代码，跨域访问允许访问的响应头的内容
        res.setHeader("Access-Control-Expose-Headers","token");

        res.setHeader("token", tokenUtil.getToken(user.getName()));

        return result;

    }

//    @RequestMapping({"/getNamelist"})
//    @ResponseBody
//    public List<User> getNamelist(User user, HttpServletRequest req, HttpSession session) throws Exception {
//        List<User> userlist = userService.getUserByName(user);
//        return userlist;
//    }


    // 用户添加
    @RequestMapping({"/yonghutianjia"})
    public String yonghutianjia(User user, HttpServletRequest req, HttpSession session) throws Exception {

        return "admin/yonghutianjia";
    }
}
